﻿using System;

namespace negoserverjni
{
    public class Header
    {
        byte[] header;
        public Header(uint length)
        {
            //VERIFIED
            header = new byte[5];
            header[0] = 20;
            header[1] = 1;
            header[2] = 0;
            header[3] = (byte)(length >> 8);
            header[4] = (byte)(length & 255);
        }
        public Header(byte[] h)
        {
            header = h;
            if (h== null ) ThrowNullException();
            if (h.Length != 5) ThrowException();
            if (
                (header[0] > (int)Status.HandshakeInProgress)
                    || (header[0] < (int)Status.HandshakeDone)
                ) ThrowExeptionStatus();
        }

        void ThrowNullException()
        {
            throw new ArgumentNullException("header null"); 
        }
        void ThrowException()
        {
            throw new ArgumentException(string.Format("length header != 5 : {0}", header.Length));
        }
        void ThrowExeptionStatus()
        {
            throw new ArgumentOutOfRangeException(string.Format("Status {0}", header[0]));
        }

        public Status AuthenticationStatus
        { get { return (Status)header[0]; } }

        public byte[] ToBuffer()
        {
            return header;
        }
        public int Length
        {
            get 
            {
                uint len = ((uint)header[3]) << 8;
                len = len + header[4];
                return (int)len;
            }
        }
    }

    public enum Status
    {
        HandshakeDone = 0x14,
        HandshakeError = 0x15,
        HandshakeInProgress = 0x16
    }
}
